<?php

namespace App\WeChat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use Exception;
use Illuminate\Database\Eloquent\InvalidCastException;
use LogicException;
use Illuminate\Contracts\Container\BindingResolutionException;
use WeChatService;
use Houdunwang\WeChat\User as WechatUserPackage;

/**
 * 微信登录
 * @package App\Http\Controllers
 */
class LoginController extends Controller
{
    /**
     * h5与pc将用户重定向到授权页面
     * @return \Illuminate\Http\Response
     */
    public function login(WechatUserPackage $wechatUser)
    {
        $userinfo = $wechatUser->init(config('site.user.wechatweb'))->snsapiUserInfo('wechat');
        $user = WeChatService::saveUser($userinfo);
        Auth::login($user);
        return redirect()->intended('/');
    }

    /**
     * APP登录
     * 需要传递包含openid/unionid及用户资料的Post数据
     * @param Request $request
     * @return void
     * @throws Exception
     * @throws InvalidCastException
     * @throws LogicException
     * @throws BindingResolutionException
     */
    public function app(Request $request)
    {
        $token = WeChatService::saveUser($request->input())->createToken('auth')->plainTextToken;
        return $this->message('登录成功', ['token' => $token]);
    }
}
